import { observable, action, toJS } from 'mobx';
import { ListViewPage, SearchPage } from 'weaver-mobile-page';
import * as Api from '../../api';
const initalState = {
  path: '',
  list: null,
  page: '',
  votingid: '',
  questionid: '',
  optionid: '',
  searchValue: '',
  searchPageStore: null,
  localeStorageKey: '',
  fileList: {},
}
const template = { default: [{ key: 'col', configs: [{ key: 'col_row', configs: [{ key: 'name' }] }] }] };
export default class PersonList {
  @observable path = initalState.path;
  @observable list = initalState.list;
  @observable page = initalState.page;
  @observable votingid = initalState.votingid;
  @observable questionid = initalState.questionid;
  @observable optionid = initalState.optionid;
  @observable searchValue = initalState.searchValue;
  @observable searchPageStore = initalState.searchPageStore;
  @observable localeStorageKey = initalState.localeStorageKey;
  @observable fileList = initalState.fileList;
  @observable loading = false;

  @action setStoreState = (params) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    })
  }

  @action clear = () => this.setStoreState(initalState);

  @action inital = () => {
    this.localeStorageKey = `resultSearchHistory__${this.page}`;
    this.list = new ListViewPage.Store({ route: this.path, id: this.page });
    this.searchPageStore = new SearchPage.Store({ route: this.path, id: 'history', template });
  }

  @action search = (search) => {
    if (this.list && this.votingid !== '') {
      let params = {...search, votingid: this.votingid};
      let _params = {...params, questionid: this.questionid};
      let __params = {..._params, optionid: this.optionid};
      let funArr = [
        { key: 'resJoin', name: 'doPerson', params }, // 已参与
        { key: 'resnotJoin', name: 'undoPerson', params }, // 未参与
        { key: 'answerList', name: 'doPersonOfQuesion', params: _params }, // 回答
        { key: 'other', name: 'doPersonOfOther', params: _params }, // 其他
        { key: 'viewList', name: 'doPersonOfInput', params: _params }, // 查看
        { key: 'optionView', name: 'doPersonOfOption', params: __params }, // 选项
      ]
      let getParams = toJS(funArr).filter(v => v.key === this.page)[0];
      getParams && this.getList(getParams.name, getParams.params)
    }
  }

  @action searchPageClear = () => {
    localStorage.removeItem(this.localeStorageKey);
    this.searchPageStore.list.setState({ data: [] });
  }

  @action getList = (name, params = {}) => {
    this.loading = true;
    Api[name](params).then(res => {
      const dataKey = res.sessionkey;
      if (name === 'doPersonOfInput') this.fileList = res.imagefile;
      if (dataKey) {
        this.list && this.list.getData({ dataKey }, () => this.loading = false, true);
      }
    })
  }
}